﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Windows.Forms;

namespace TCommon.Util
{
    public class HttpUtil
    {
        public static object SendRequest<T>(string url, T param, Type responseType)
        {
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
                var stream = new MemoryStream();
                serializer.WriteObject(stream, param);
                byte[] dataBytes = new byte[stream.Length];
                stream.Position = 0;
                stream.Read(dataBytes, 0, (int)stream.Length);
                string dataString = Encoding.UTF8.GetString(dataBytes);
                stream.Close();
                request.Method = "POST";
                request.ContentType = "application/json";

                var requestByte = Encoding.UTF8.GetBytes(dataString);
                request.ContentLength = requestByte.Length;
                using (var requestStream = request.GetRequestStream())
                {
                    requestStream.Write(requestByte, 0, requestByte.Length);
                    var response = (HttpWebResponse)request.GetResponse();
                    StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                    var returnString = sr.ReadToEnd();
                    var responseStream = new MemoryStream(Encoding.UTF8.GetBytes(returnString));
                    DataContractJsonSerializer seri = new DataContractJsonSerializer(responseType);
                    return seri.ReadObject(responseStream);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
                return null;
            }
        }
    }
}
